﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;

namespace MyMovies
{
    internal class ScanFolders
    {
        private static BackgroundWorker bw = new BackgroundWorker();
        private static bool firstTime = true;
        private static string status = string.Empty;
        private static DateTime ScanDate;

        public delegate void MessageEventHandler(MessageEventArgs e);
        public static event MessageEventHandler ScanStart;
        public static event MessageEventHandler ScanEnd;
        public static event MessageEventHandler ScanProgress;

        public static List<FileDuplicated> DuplicatedFiles = new List<FileDuplicated>();

        public static void Scan(string folder)
        {
            if (firstTime)
            {
                bw.WorkerReportsProgress = true;
                bw.WorkerSupportsCancellation = true;
                bw.DoWork += new DoWorkEventHandler(bw_DoWork);
                bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
                bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
                firstTime = false;
            }

            if (bw.IsBusy != true)
            {
                if (ScanStart != null)
                    ScanStart(new MessageEventArgs(Properties.Resources.ScanFolder));

                bw.RunWorkerAsync(folder);
            }
        }

        private static void StopScan()
        {
            if (bw.WorkerSupportsCancellation == true)
            {
                bw.CancelAsync();
            }
        }

        private static void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if ((e.Cancelled == true))
            {
                status = Properties.Resources.Canceled;
            }
            else if (!(e.Error == null))
            {
                status = string.Format(Properties.Resources.Error, e.Error.Message);
            }
            else
            {
                status = Properties.Resources.Completed;
            }
            if (ScanEnd != null)
                ScanEnd(new MessageEventArgs(status));
        }

        private static void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
        }

        private static void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            if ((worker.CancellationPending == true))
            {
                e.Cancel = true;
                return;
            }
            string path = e.Argument.ToString();

            DuplicatedFiles.Clear();
            ScanDate = DateTime.Now;

            foreach (string directory in Directory.GetDirectories(path))
                AddFiles(directory, -1);

            TableGenre.RemoveOld(ScanDate);
            TableMovies.RemoveOld(ScanDate);
            TableVideoFileInfo.RemoveOld();
            TableAudioFileInfo.RemoveOld();
        }

        private static void AddFiles(string directory, int genreID)
        {
            if (genreID < 0)
            {
                if (directory.Contains(@"\Serie\"))
                    genreID = TableGenre.SearchInsert(string.Concat("Serie - ", Path.GetFileName(directory)), ScanDate);
                else
                    if (!directory.EndsWith(@"\Serie"))
                        genreID = TableGenre.SearchInsert(Path.GetFileName(directory), ScanDate);
            }

            if (!directory.EndsWith(@"\Serie"))
                foreach (string file in Directory.GetFiles(directory))
                {
                    string ext = Path.GetExtension(file);
                    if (string.Compare(ext, ".avi", true) == 0 ||
                        string.Compare(ext, ".mkv", true) == 0 ||
                        string.Compare(ext, ".mpg", true) == 0)
                        AddToArchive(Path.GetFileName(file), genreID, directory, ScanDate);
                }
            foreach (string subdirectory in Directory.GetDirectories(directory))
                if (!subdirectory.StartsWith("_"))
                    AddFiles(subdirectory, genreID);
        }

        private static void AddToArchive(string file, int genreid, string path, DateTime scandate)
        {
            if (ScanProgress != null)
                ScanProgress(new MessageEventArgs(file));

            string findPath = TableMovies.SearchInsert(file, genreid, path, scandate);
            if (path.Remove(0, path.IndexOf("Video") + 6) != findPath)
                DuplicatedFiles.Add(new FileDuplicated() { Path1 = path, Path2 = findPath, File = file });
        }
    }

    public class MessageEventArgs : EventArgs
    {
        public string Message { get; private set; }

        public MessageEventArgs(string file)
        {
            Message = file;
        }
    }

    public class FileDuplicated
    {
        public string Path1 { get; set; }

        public string Path2 { get; set; }

        public string File { get; set; }
    }
}